//
//  ComposeViewController.m
//  weibo-OC
//
//  Created by diyuyma on 16/2/24.
//  Copyright © 2016年 zhangkaiyun. All rights reserved.
//

#import "ComposeViewController.h"
#import "UserAccountViewModel.h"
#import "SVProgressHUD.h"
#import "Masonry.h"
#import "AFNetworking.h"
#import "NetworkTools.h"
#import "PictureSelectorViewController.h"

@interface ComposeViewController ()<UITextViewDelegate>
@property (nonatomic, strong)UITextView *textView;
@property (nonatomic, strong)UILabel *placeHolderLabel;
@property (nonatomic, strong)UIToolbar *toolBar;
// 图片选择器
@property (nonatomic, strong)PictureSelectorViewController *selectorVC;
@end

@implementation ComposeViewController
- (void)selectPicture {
    
    [self.selectorVC.view mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(@(224+80+40));
    }];
}

- (PictureSelectorViewController *)selectorVC {
    if (_selectorVC == nil) {
        _selectorVC = [[PictureSelectorViewController alloc] init];
    }
    return _selectorVC;
}


- (UIToolbar *)toolBar {
    if (_toolBar == nil) {
        _toolBar = [[UIToolbar alloc] init];
    }
    return _toolBar;
}

- (UILabel *)placeHolderLabel {
    if (_placeHolderLabel == nil) {
        _placeHolderLabel = [[UILabel alloc] init];
        [_placeHolderLabel initWithLabel:@"分享新鲜事..." WithColor:[UIColor lightGrayColor] WithSize:18 WithMargin:0];
    }
    return _placeHolderLabel;
}
- (UITextView *)textView {
    if (_textView ==nil) {
        _textView = [[UITextView alloc] init];
        _textView.delegate = self;
        _textView.font = [UIFont systemFontOfSize:18];
        _textView.textColor = [UIColor darkGrayColor];
        // 设置键盘消失模式
        _textView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
        // 设置弹簧效果开启
        _textView.alwaysBounceVertical = true;
    }
    return _textView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    [self setupUI];
}

- (void)setupUI {
    [self setNavBar];
    // 设置文本输入
    [self setupTextView];
    
    [self setupToolBar];
    
    // 添加图片选择控制器视图
    [self setSelectorView];
    // 注册通知
    [self registerNotification];
    
}

- (void)setSelectorView {
    //添加子视图控制器
    [self addChildViewController:self.selectorVC];

    //添加视图
    [self.view addSubview:self.selectorVC.view];

    // 调整视图层次结构
    [self.view bringSubviewToFront:self.toolBar];
    [self.selectorVC.view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.and.right.equalTo(self.view);
        make.height.equalTo(@0);
    }];
}

- (void)registerNotification {
    // 添加通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
}
// 移除通知
- (void)deinit {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

// 通知响应方法
- (void)keyboardWillChange: (NSNotification *)n {
    // 获取动画事件
    double duration = [n.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    CGRect rect = [n.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    //修改 toolBar约束
    //获取键盘高度
    CGFloat offset = -kScreenHeight + rect.origin.y;
    [self.toolBar mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(offset);
    }];
    [UIView animateWithDuration:duration animations:^{
       // 强制刷新
        [self.view layoutIfNeeded];
    }];
}


- (void)textViewDidChangeSelection:(UITextView *)textView {
    // 设置展位文本隐藏
    self.placeHolderLabel.hidden = [self.textView hasText];
    // 设置发布按钮的交互
    self.navigationItem.rightBarButtonItem.enabled = [self.textView hasText ];
}

- (void)setupTextView {
    [self.view addSubview:self.textView];
    self.textView.backgroundColor = [[[UIColor alloc] init] randomColor];
    
    // 设置约束
    [self.textView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.and.right.equalTo(self.view);
        make.height.equalTo(@(self.view.bounds.size.height / 3));
    }];

    [self.textView addSubview:self.placeHolderLabel];
    [self.placeHolderLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.textView.mas_top).with.offset(8);
        make.left.equalTo(self.textView.mas_left).with.offset(5);
    }];
}

- (void)setupToolBar {
    [self.view addSubview:self.toolBar];
    
    // 设置约束
    [self.toolBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.equalTo(self.view);
        make.height.equalTo(@40);
    }];
    
    //设置 toolbar的按钮 以及点击事件
    NSMutableArray *items = [NSMutableArray arrayWithCapacity:10];
    NSArray *itemSettings = @[@{@"imageName" : @"compose_toolbar_picture", @"actionName" : @"selectPicture"},
                              @{@"imageName" : @"compose_mentionbutton_background"},
                              @{@"imageName" : @"compose_trendbutton_background"},
                              @{@"imageName" : @"compose_emoticonbutton_background"},
                              @{@"imageName" : @"compose_add_background"}];
    
    for (NSDictionary *dict in itemSettings) {
        UIBarButtonItem *item = [[UIBarButtonItem alloc] init];
        [item initWithImageName:dict[@"imageName"] Target:self ActionName:dict[@"actionName"]];
        [items addObject:item];
        
        //实例化弹簧
        UIBarButtonItem *space = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:(UIBarButtonSystemItemFlexibleSpace) target:nil action:nil];
        [items addObject:space];
    }
    //删除最后一个弹簧
    [items removeLastObject];
    
    self.toolBar.items = items;
}

- (void)close {
    
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)send {
    NSString *urlString = @"https://upload.api.weibo.com/2/statuses/upload.json";
    NSString *token = [[UserAccountViewModel alloc] init].token;
    NSLog(@"%@", token);
    if (token == nil) {
        [SVProgressHUD showErrorWithStatus:@"客官,您还未登陆哦噢噢噢"];
        return ;
    }
    
    if (self.selectorVC.imageList.count >= 1) {
        NSData *imageData = UIImagePNGRepresentation(self.selectorVC.imageList[0]);
        NSMutableDictionary *parameters = [NSMutableDictionary dictionaryWithCapacity:10];
        [parameters setObject:token forKey:@"access_token"];
        [parameters setObject:self.textView.text forKey:@"status"];
        
        [[NetworkTools sharedTools] uploadImage:urlString WithParmaters:parameters WithData:imageData WithFinished:^(NSDictionary *result, NSError *error) {
            
            if (error != nil) {
                [SVProgressHUD showErrorWithStatus:@"客官,您还未登陆哦噢噢噢"];
                return ;
            }
            [SVProgressHUD showSuccessWithStatus:@"发布Weibo成功"];
            [self close];
            }];
    }
}



- (void)setNavBar {
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"关闭" style:UIBarButtonItemStylePlain target:self action:@selector(close)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"发布" style:UIBarButtonItemStylePlain target:self action:@selector(send)];
    self.navigationItem.rightBarButtonItem.enabled = false;
    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 40)];
    self.navigationItem.titleView = titleView;
    
    //添加导航栏 发布信息的UIlabel
    UILabel *titleLable = [[UILabel alloc]init];
    [titleLable initWithLabel:@"发微博" WithColor:[UIColor darkGrayColor] WithSize:17 WithMargin:0];
    UILabel *nameLabel = [[UILabel alloc]init];
    [nameLabel initWithLabel:[[UserAccountViewModel alloc] init].userName WithColor:[UIColor lightGrayColor] WithSize:14 WithMargin:0];
    
    // 添加子视图
    [titleView addSubview:titleLable];
    [titleView addSubview:nameLabel];
    
    // 设置约束
    [titleLable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(titleView.mas_top);
        make.centerX.equalTo(titleView.mas_centerX);
    }];
    
    [nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(titleView.mas_bottom);
        make.centerX.equalTo(titleView.mas_centerX);
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

}



@end
